package cn.rocky.zuosheng;

public class CodeMergeSort {

    // 比较行为信息留下来了被保留下来了,整体有序的部分去更下一个进行比较
    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }

    public static void process(int[] arr, int L, int R) {
        if (L == R) {
            return;
        }
        int mid = L + ((R - L) >> 1);
        process(arr, L, mid);
        process(arr, mid + 1, R);
        merge(arr, L, mid, R);
    }

    public static void merge(int[] arr, int L, int Mid, int R) {
        // 辅助空间
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = Mid + 1;
        // p1,p2不越界的情况下 比较值 然后进行归并
        while (p1 <= Mid && p2 <= R) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= Mid) {
            help[i++] = arr[p1++];
        }
        while (p2 <= Mid) {
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
    }
}
